import { Inject, Provide } from '@midwayjs/core'
import { CacheManager } from '@ttou/midway-cache'

import { ConfigService } from '@/service'
import { CacheKeyUtil } from '@/util'

import { FindOnlinePageDTO } from './online.dto'

@Provide()
export class OnlineService {
  @Inject()
  configService: ConfigService

  @Inject()
  cacheManager: CacheManager

  async handleFindPage(dto: FindOnlinePageDTO) {
    const { userName } = dto
    const tokenKey = CacheKeyUtil.getTokenKey('*')
    const keys = await this.cacheManager.store.keys(`${tokenKey}`)

    const list = [] as IOnlineInfo[]

    for (const key of keys) {
      const item = await this.cacheManager.get<IOnlineInfo>(key)

      if (userName) {
        if (item.userName === userName) {
          list.push(item)
        }
      } else {
        list.push(item)
      }
    }

    return list
  }

  async handleOffline(id: string) {
    const isSoloLogin = await this.configService.isSoloLogin()
    const tokenKey = CacheKeyUtil.getTokenKey(id)

    if (isSoloLogin) {
      const { userId } = await this.cacheManager.get<IOnlineInfo>(tokenKey)

      const userKey = CacheKeyUtil.getUserKey(userId)

      await this.cacheManager.del(userKey)
    }

    await this.cacheManager.del(tokenKey)
  }
}
